import { memo, useEffect } from "react"
import { useForm, FormProvider } from "react-hook-form"
import Selection from "@/components/form_item/Selection"
import { Container, ToolBar } from "@/pages/TransactionRecordPage/components/Wrappers"
import StateDisplay from "@/pages/TransactionRecordPage/components/StateDisplay"
import FootDataCount from "@/pages/TransactionRecordPage/components/FootDataCount"
import { ErrorDetails, BaseFormType } from "@/pages/TransactionRecordPage/types"
import { timeRangeOptions, ALL, TODAY } from "@/pages/TransactionRecordPage/constants"

interface Props<T> {
    children: React.ReactNode
    statusOptions?: { value: string | undefined; name: string }[]
    value?: BaseFormType
    onChange?: (formData: BaseFormType) => void
    list?: T[]
    loading?: boolean
    error?: ErrorDetails
    hasMore?: boolean
    myRef?: React.RefObject<HTMLDivElement | null>
    hideSelectType?: boolean
}

const Component = <T extends object>(props: Props<T>) => {
    const methods = useForm()
    const { handleSubmit, setValue } = methods

    const onSubmit = async (data: BaseFormType) => {
        console.log(data)
        onChange?.(data)
    }

    useEffect(() => {
        const value = props.value || {}
        const { type, time_flag } = value
        setValue("type", type || ALL)
        setValue("time_flag", time_flag || TODAY)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [props.value])

    const {
        children,
        statusOptions,
        hideSelectType,
        onChange,
        list = [],
        loading,
        error,
        hasMore,
        myRef,
    } = props
    return (
        <>
            <ToolBar>
                <FormProvider {...methods}>
                    {!hideSelectType && (
                        <Selection
                            style={{ flex: 1 }}
                            fieldName="type"
                            onClick={handleSubmit(onSubmit)}
                            selectItems={statusOptions}
                        />
                    )}
                    <Selection
                        style={{ flex: 1 }}
                        fieldName="time_flag"
                        onClick={handleSubmit(onSubmit)}
                        selectItems={timeRangeOptions}
                    />
                </FormProvider>
            </ToolBar>
            {list?.length > 0 ? (
                <Container>{children}</Container>
            ) : (
                <StateDisplay
                    loading={loading}
                    error={error}
                />
            )}
        </>
    )
}

export default memo(Component) as typeof Component
